package com.itheima.controller;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.common.R;
import com.itheima.dto.AddAddressDTO;
import com.itheima.dto.SetDefaultVo;
import com.itheima.pojo.AddressBook;
import com.itheima.service.AddressBookService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author 小帅蓝
 * @Date 2022/6/22 19:17
 */
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Resource
    private AddressBookService addressBookService;

    @GetMapping("/default")
    public R<AddressBook> queryDefault() {
        return addressBookService.queryDefault();
    }

    @PutMapping("/default")
    public R<AddressBook> setDefault(@RequestBody SetDefaultVo setDefaultVo) {
        AddressBook addressBook = new AddressBook();
        BeanUtil.copyProperties(setDefaultVo, addressBook);

        return addressBookService.setDefault(addressBook);
    }

    @GetMapping("/list")
    public R<List<AddressBook>> queryAll() {
        return addressBookService.queryAll();
    }

    @GetMapping("/{id}")
    public R<AddressBook> queryById(@PathVariable String id) {
        return addressBookService.queryById(id);
    }

    @PostMapping
    public R<AddressBook> addAddressBook(@RequestBody AddAddressDTO addAddressDTO) {
        AddressBook addressBook = new AddressBook();
        BeanUtil.copyProperties(addAddressDTO, addressBook);
        return addressBookService.addAddressBook(addressBook);
    }

    @DeleteMapping
    public R<String> deleteAddressBook(String ids) {
        boolean result = addressBookService.deleteAddressBook(ids);
        return result ? R.success("删除成功!") : R.error("删除失败！");
    }

    @PutMapping
    public R<String> updateAddressBook(@RequestBody AddressBook addressBook) {
        return addressBookService.updateAddressBook(addressBook);
    }

}
